package com.td.erhome.ui.bughouse;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.td.erhome.R;
import com.td.erhome.adapter.BugHouseListAdapter;
import com.td.erhome.base.BaseActivity;
import com.td.erhome.models.BaseBean;
import com.td.erhome.models.BugHouseFiltrateBean;
import com.td.erhome.models.CityInfoLitePal;
import com.td.erhome.models.HouseBean;
import com.td.erhome.models.MoreTotleBean;
import com.td.erhome.net.Api;
import com.td.erhome.net.BaseSubscriber;
import com.td.erhome.utils.ConstUtils;
import com.td.erhome.utils.DialogUtils;
import com.td.erhome.utils.RxBus;
import com.td.erhome.utils.TypeUtils;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class BugHouseListActivity extends BaseActivity {

    @Bind(R.id.recyclview)
    XRecyclerView mRecyclerView;
    @Bind(R.id.ra_group)
    RadioGroup mRadioGroup;
    @Bind(R.id.view_line)
    View line;
    @Bind(R.id.ch_area)
    CheckBox mChArea;
    @Bind(R.id.ch_price)
    CheckBox mChPrice;
    @Bind(R.id.ground)
    View mGround;
    @Bind(R.id.ch_hx)
    CheckBox mChHx;
    @Bind(R.id.ch_more)
    CheckBox mChMore;
    @Bind(R.id.et_search)
    EditText mEtSearch;
    @Bind(R.id.img_back)
    ImageView mImgBack;
    @Bind(R.id.tv_error)
    TextView mTvError;
    @Bind(R.id.altha)
    RelativeLayout nAltha;
    private Subscription mSubscribe;
    private DialogUtils mDialogUtils;
    private List<HouseBean.SellHouseListBean> mhouse_list = new ArrayList<>();
    private long mArea_id = 0; //街道id
    private String mPrice = "1";//价格
    private int mType_of_rooms = 1; //几室
    private BugHouseListAdapter mAdapter;
    private int page;
    private Subscription mSubscribe1;
    private int house_area = 1;
    private int decCondition= 1;
    private int orientations= 1;
    private int house_age= 1;
    private int area1;
    private int area2;
    private Subscription mSubscribe2;
    private int mTotal_count;
    private boolean isFirst = true;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bug_house_list;
    }

    @Override
    protected void initView() {
        mEtSearch.setText(getIntent().getStringExtra("key"));
        nAltha.setBackgroundColor(getResources().getColor(R.color.color_0b9676));
        nAltha.getBackground().setAlpha(255);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallPulse);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallPulse);
        mAdapter = new BugHouseListAdapter(this,mhouse_list);
        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mAdapter.clearData();
                page =1;
                getData();
            }
            @Override
            public void onLoadMore() {

                if (mTotal_count>mAdapter.mhouse_list.size()){
                    page++;
                    getData();
                }else {
                    mRecyclerView.refreshComplete();
                }
            }
        });



        //搜索框的监听
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //是否是回车键
                if(actionId ==EditorInfo.IME_ACTION_SEARCH){
                 // 先隐藏键盘
                    ((InputMethodManager) mEtSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    reInit();
                }
                return false;
            }
        });

        mSubscribe = RxBus.getInstance().toObserverable(BugHouseFiltrateBean.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BugHouseFiltrateBean>() {
                    @Override
                    public void call(BugHouseFiltrateBean bugHouseFiltrateBean) {
                        mArea_id = bugHouseFiltrateBean.area_id;
                        mPrice = bugHouseFiltrateBean.price;
                        mType_of_rooms = bugHouseFiltrateBean.type_of_rooms;
                        area1 = bugHouseFiltrateBean.area1_point;
                        area2 = bugHouseFiltrateBean.area2_point;

                        List<CityInfoLitePal> cityInfoLitePals = DataSupport.where("area_id = ?", mArea_id+"").find(CityInfoLitePal.class);
                        mChArea.setText(cityInfoLitePals.size()==0?"区域":cityInfoLitePals.get(0).area_name);
                        mChPrice.setText(TypeUtils.getPriceType(mPrice));
                        mChHx.setText(TypeUtils.getHxType(mType_of_rooms));

                        mAdapter.clearData();
                        page=1;
                        getData();
                    }
                });


        //更多的选择回调

        mSubscribe1 = RxBus.getInstance().toObserverable(MoreTotleBean.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<MoreTotleBean>() {

                    @Override
                    public void call(MoreTotleBean moreTotleBean) {
                        house_area = moreTotleBean.house_area;
                        decCondition = moreTotleBean.decCondition;
                        orientations = moreTotleBean.orientations;
                        house_age = moreTotleBean.house_age;

                        mAdapter.clearData();
                        page =1;
                        getData();
                    }
                });


        //收藏 取消收藏涮新
        mSubscribe2 = RxBus.getInstance().toObserverable(Integer.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer i) {
                        if (i==ConstUtils.FINISH_CON){
                            mAdapter.clearData();
                            page =1;
                            getData();
                        }
                    }
                });

        mDialogUtils = new DialogUtils();
        getData();
    }


    //初始化搜索条件
    public void reInit(){
         mArea_id = 0; //街道id
          mPrice = "1";//价格
          mType_of_rooms = 1; //几室
          page = 1;
          house_area = 1;
          decCondition= 1;
          orientations= 1;
          house_age= 1;
          area1=0;
          area2=0;
        mChArea.setText("区域");
        mChPrice.setText(TypeUtils.getPriceType(mPrice));
        mChHx.setText("户型");
        mAdapter.clearData();
        getData();
    }

    @Override
    protected void releaseResource() {
        if (!mSubscribe.isUnsubscribed()){
            mSubscribe.unsubscribe();
        } if (!mSubscribe1.isUnsubscribed()){
            mSubscribe1.unsubscribe();
        }
        if (mSubscribe2.isUnsubscribed()){
            mSubscribe2.unsubscribe();
        }if (mAdapter.mSubscribe.isUnsubscribed()){
            mSubscribe.unsubscribe();
        }
        mDialogUtils = null;
    }
    
    @OnClick({R.id.ch_area, R.id.ch_price,R.id.ch_hx, R.id.ch_more,
            R.id.img_back,R.id.tv_error})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ch_area:
                mDialogUtils.initPopChoiceCarWindow(this, line, mGround, mChArea,area1,area2);
                break;
            case R.id.ch_price:
                mDialogUtils.initPopChoicePriceWindow(this, line, mGround, mChPrice,mPrice);
                break;
            case R.id.ch_hx:
                mDialogUtils.initPopChoiceHxWindow(this, line, mGround, mChHx,mType_of_rooms);
                break;
            case R.id.ch_more:
                mDialogUtils.initPopChoiceMoreWindow(this, line, mGround, mChMore,house_area,decCondition,orientations,house_age);
                break;
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_error:
                mAdapter.clearData();
                page =1;
                getData();
                break;
        }
    }

     public void getData(){
         HashMap<String, Object> params = new HashMap<>();
         params.put("page", page);
         params.put("total_amount", mPrice);
         params.put("house_area",house_area);
         params.put("decCondition",decCondition);
         params.put("house_age",house_age);
         params.put("orientations",orientations);
         params.put("keyword",mEtSearch.getText().toString());
         params.put("type_of_rooms", mType_of_rooms);
         if (mArea_id!=0){
             params.put("street_id",mArea_id);
         }
         Api.getRetrofit().getOnSellHouseList(params)
                 .subscribeOn(Schedulers.io())
                 .observeOn(AndroidSchedulers.mainThread())
                 .subscribe(new BaseSubscriber<BaseBean<HouseBean>>(BugHouseListActivity.this){
                     @Override
                     public void onCompleted() {
                         super.onCompleted();
                         mRecyclerView.refreshComplete();
                     }
                     @Override
                     public void onError(Throwable e) {
                         super.onError(e);
                         mRecyclerView.refreshComplete();
                         mTvError.setVisibility(View.VISIBLE);
                     }
                     @Override
                     public void onNext(BaseBean<HouseBean> houseBeanBaseBean) {
                         super.onNext(houseBeanBaseBean);

                         String s = houseBeanBaseBean.toString();
                         mTotal_count = houseBeanBaseBean.getData().total_count;
                         mhouse_list = houseBeanBaseBean.getData().house_list;
                         mAdapter.addData(mhouse_list);
                         mRecyclerView.refreshComplete();
                         if (mAdapter.mhouse_list.size()==0){
                             mTvError.setVisibility(View.VISIBLE);
                         }else {
                             mTvError.setVisibility(View.GONE);
                         }

                         if (isFirst){
                             DialogUtils.mesg(BugHouseListActivity.this);
                             isFirst = false;
                         }
                     }
                 });
     }

}
